package com.aaa.member.service.impl;

import com.aaa.common.constant.ExceptionConstant;
import com.aaa.common.constant.ReturnCode;
import com.aaa.common.util.Result;
import com.aaa.member.dao.TbMemberDao;
import com.aaa.member.entity.TbMember;
import com.aaa.member.service.TbMemberService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * (TbMember)表服务实现类
 *
 * @author makejava
 * @since 2020-11-20 14:35:40
 */
@Service("tbMemberService")
public class TbMemberServiceImpl implements TbMemberService {
    @Resource
    private TbMemberDao tbMemberDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public TbMember queryById(Integer id) {
        System.out.println("会员id"+id);
        return this.tbMemberDao.queryById(id);
    }

    /**
     * 前台会员查询所有的订单
     * @param memberId
     * @param orderstate
     * @return
     */
    @Override
    public List<Map> queryAllOrder(Integer memberId, Integer orderstate) {
        return tbMemberDao.queryAllOrder(memberId,orderstate);
    }

    /**
     * 后台分页+查询所有会员信息
     * @param pageNo
     * @param pageSize
     * @param tbMember
     * @return
     */
    @Override
    public Result queryAllMember(Integer pageNo, Integer pageSize, TbMember tbMember) {
        //分页
        PageHelper.startPage(pageNo, pageSize);
        PageInfo<TbMember> pageInfo = new PageInfo<TbMember>(tbMemberDao.queryAll(tbMember));
        return new Result(ReturnCode.SUCCESSS.getCode(),
                ReturnCode.SUCCESSS.getMsg(), pageInfo);
    }

    /**
     * 根据用户名，使用状态模糊查询客户所有优惠券
     *
     * @param
     * @return
     */
    @Override
    public Result queryMemberCoupon(Integer pageNo, Integer pageSize, String username, Integer usestatus) {
        //分页
        PageHelper.startPage(pageNo, pageSize);
        System.out.println(username + "----" + usestatus);
        PageInfo<Map> pageInfo = new PageInfo<Map>(tbMemberDao.queryMemberCoupon(username, usestatus));
        return new Result(ReturnCode.SUCCESSS.getCode(),
                ReturnCode.SUCCESSS.getMsg(), pageInfo);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<TbMember> queryAllByLimit(int offset, int limit) {
        return this.tbMemberDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param tbMember 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(TbMember tbMember) {
        /*  Map userInfo = (Map)session.getAttribute("userInfo");
        if(userInfo!=null){
            map.put("userName",userInfo.get("user_name"));
        }*/
        //map.put("userName", SessionUtil.getUserName());
        //盐值
        String salt = UUID.randomUUID().toString().substring(0, 15);
        tbMember.setPwSalt(salt);
        //随机盐值，放入数据库
        //map.put("salt", salt);
        //获取用户输入的原始密码
        String password = tbMember.getPassword();
        //使用SHA512加密算法，把原始密码和随机到的盐值一起进行运算，得到密码，存入数据
        //Sha512Hash(Object source, Object salt, int hashIterations)
        //          第1个参数，原始密码，第2参数，随机盐值  第3参数 hash次数
        //           和配置类中配置的加密算法名称和hash次数一致 com.aaa.sbms.config.ShiroConfig
        Sha512Hash sha512Hash = new Sha512Hash(password, salt, 1024);
        //设置参数
        tbMember.setPassword(sha512Hash.toString());
        //map.put("password",sha512Hash.toString());
        return this.tbMemberDao.insert(tbMember);
    }

    /**
     * 修改数据
     *
     * @param tbMember 实例对象
     * @return 实例对象
     */
    @Override
    public TbMember updatePassword(TbMember tbMember) {
        //获取盐值
        String salt = UUID.randomUUID().toString().substring(0, 15);
        tbMember.setPwSalt(salt);
        //获取用户输入的原始密码
        String password = tbMember.getPassword();
        Sha512Hash sha512Hash = new Sha512Hash(password, salt, 1024);
        //设置参数
        tbMember.setPassword(sha512Hash.toString());
        this.tbMemberDao.update(tbMember);
        return this.queryById(tbMember.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.tbMemberDao.deleteById(id) > 0;
    }

    @Override
    public Result memberlogin(String username, String password) {
        //收集用户输入
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        //获取登录对象
        Subject crrentUser = SecurityUtils.getSubject();
        //判断是否已经人认证
        if (!crrentUser.isAuthenticated()) {
            try {
                //提交数据  交给SecurityManager进行认证   登录
                crrentUser.login(token);
                //记录session
                Session session = crrentUser.getSession();
                session.setAttribute("userInfo",crrentUser.getPrincipal());
                return new Result(ReturnCode.SUCCESSS.getCode(),
                        ReturnCode.SUCCESSS.getMsg(), null);
            } catch (AuthenticationException e) {
                e.printStackTrace();
            }
        }
        return new Result(ExceptionConstant.EORRO_USERNAME_OR_PASSWORD.getErrorCode(),
                ExceptionConstant.EORRO_USERNAME_OR_PASSWORD.getErrorMessage(), null);
    }
    @Override
    public TbMember selectbyusername(String username) {
        return tbMemberDao.selectbyusername(username);
    }
}